// pages/index/index.js
const app = getApp()
import {
  addNote,
  quearyAllNoteByLocal
} from "./../../api/nots.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img: {
      press: "./../../image/index_btn.png",
      normal: "./../../image/logo_btn_normal.png",
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      imgUrl: this.data.img.normal
    })
  },

  onImagePress() {
    console.log("------onImagePress")
    this.setData({
      imgUrl: this.data.img.press
    })
  },
  onImageNormal() {
    console.log("------onImageNormal")
    this.setData({
      imgUrl: this.data.img.normal
    })

  },
  onClick() {
    quearyAllNoteByLocal().then(list => {
      if (list.length > 0) {
        const that = this
        wx.showModal({
          title: '提示',
          content: '检测到本地有' + list.length + "数据，是否同步到云端",
          success(res) {
            if (res.confirm) {
              that.upload(list)
            } else if (res.cancel) {
              that.goHome()
            }
          }
        })
      } else {
        this.goHome()
      }
    })
  },
  upload(list) {
    let count = 0
    const len = list.length
    const title = "同步中(" + count + '/' + len + ")"
    wx.showLoading({
      title: title,
      mask: true
    })

    list.forEach(item => {
      addNote(item).then(res => {
        count++
        if (count === len) {
          wx.hideLoading()
          wx.removeStorageSync('notes')
          this.goHome()
        }
      })
    })
  },
  goHome() {
    wx.redirectTo({
      url: './../home/home',
    })
  }
})